/*
 * Layer.cpp
 *
 *  Created on: 30/12/2011
 *      Author: faust
 */

#include "Layer.h"
#include "SampleUtils.h"

Layer::Layer()
{

}

Layer::~Layer()
{
	if (models != 0) delete[]models;

}

Layer* Layer::create(JNIEnv* env, jobject layerObject)
{

	Layer* layer = new Layer();

	//LOG("Layer::create - start loading layer");

	jclass jLayerClass = env->GetObjectClass(layerObject);
	jmethodID getModelCountMethodID = env->GetMethodID(jLayerClass,
													"getModelCount", "()I");

	if (getModelCountMethodID == 0)
	{
		LOG("Layer::create - Function getModelCount not found.");
		return NULL;
	}


	int modelCount = env->CallIntMethod(layerObject, getModelCountMethodID);
	if (!modelCount)
	{
		LOG("Layer::create - getModelCount returned zero.");
	}

	layer->modelCount = modelCount;
	layer->models = new Model*[modelCount];

	jmethodID getModelMethodID = env->GetMethodID(jLayerClass,
		"getModel", "(I)Lcom/Domain/Model;");

	if (getModelMethodID == 0)
	{
		LOG("Layer::create - Function getModel not found.");
		return NULL;
	}

	// Get the marker id (-1 needed to correlate layer id with trackable id)
	layer->markerId = UtilsJNI::getJavaInt(env, layerObject, "getMarkerId", "Layer::create") -1;

	// Get the width attribute
	layer->width = UtilsJNI::getJavaFloat(env, layerObject, "getWidth", "Layer::create");

	// Register the Models
	for (int i = 0; i < modelCount; ++i)
	{

		jobject modelObject = env->CallObjectMethod(layerObject, getModelMethodID, i);
		if (modelObject == NULL)
		{
			LOG("Layer::create - GetModel() returned zero pointer");
			return NULL;
		}

		layer->models[i] = Model::create(env, modelObject, layer->width);

	}

	layer->selectedModel = 0;

	//LOG("Layer::create - layer loaded successfully");
	return layer;
}
